package com.fitns.user.service.user;

import com.fitns.user.aop.annations.ZhhwAnnotation;
import com.fitns.user.dao.user.*;
import com.fitns.user.dto.user.RoleCondition;
import com.fitns.user.dto.user.RoleVO;
import com.fitns.user.dto.user.UserVO;
import com.fitns.user.exception.RoleMsgCode;
import com.fitns.user.exception.ServiceException;
import com.fitns.user.model.enums.DataPermissionType;
import com.fitns.user.model.user.Privilege;
import com.fitns.user.model.user.Role;
import com.fitns.user.model.user.RolePrivilege;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoleilu.hutool.lang.Validator;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * Created by zhou  on 2018/08/02
 *
 */


@Service
public class RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserService userService;

    @Autowired
    private PrivilegeDao privilegeDao;

    @Autowired
    private RolePrivilegeDao rolePrivilegeDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private UserDao userDao;


    @ZhhwAnnotation
    public Role insert(RoleVO roleVo){
        this.validateRoleAdd(roleVo);
   //     this.setRoleDataPremission(roleVo);
        List<RoleVO> roleVOS=roleDao.search(roleVo);
        if(Validator.isNotNull(roleVOS)&&roleVOS.size()!=0){
            throw ServiceException.create(RoleMsgCode.ROLE_MESSAGE_EXIST);
        }
        Long currentId=userService.currentUser().getId();
        roleVo.setCreateId(currentId);
        Role role=new Role();
        BeanUtils.copyProperties(roleVo,role);
        roleDao.insert(role);
        roleVo.setId(role.getId());
        processRolePrivilege(roleVo);
        return role;


    }


    @Transactional
    public void processRolePrivilege(RoleVO roleVO){
       if(Validator.isNull(roleVO.getAddPrivilegeIds())&&Validator.isNull(roleVO.getRemovePrivilegeIds())){
           return;
       }

       //角色添加权限
       List<Long> addPrivilegeIds=roleVO.getAddPrivilegeIds();
       List<Privilege> privileges=privilegeDao.seletBatchs(addPrivilegeIds);
       List<Long> allPrivilegeIds=privileges.parallelStream().map(Privilege::getId).collect(Collectors.toList());
       if(!allPrivilegeIds.containsAll(addPrivilegeIds)){
            throw ServiceException.create(RoleMsgCode.ROLR_PRIVILEGE_NOT_EXIST);
        }
        addPrivilegeIds.forEach(privilegeId->{
            RolePrivilege rolePrivilege=new RolePrivilege();
            rolePrivilege.setRoleId(roleVO.getId());
            rolePrivilege.setPrivilegeId(privilegeId);
            rolePrivilegeDao.insert(rolePrivilege);
        });


       List<Long> removePrivilegeIds=roleVO.getRemovePrivilegeIds();
       if(CollectionUtil.isNotEmpty(removePrivilegeIds)){
           rolePrivilegeDao.deleteBatchs(removePrivilegeIds);
       }

    }

    /**
     *
     * 功能描述: 验证角色必填信息是否为空，角色名称是否重复
     *
     */
    public void validateRoleAdd(RoleVO roleVO){
        if(Validator.isNull(roleVO)){
            throw ServiceException.create(RoleMsgCode.ROLE_IS_NULL);
        }
        if(Validator.isNull(roleVO.getName())||Validator.isNull(roleVO.getDescription())
                ||Validator.isNull(roleVO.getAddPrivilegeIds())){
            throw ServiceException.create(RoleMsgCode.ROLE_MESSAGE_NOT_COMPLATE);
        }
        RoleVO roleVO1=roleDao.searchByName(roleVO.getName(),roleVO.getCreateId());
        if(Validator.isNotNull(roleVO1)){
            throw ServiceException.create(RoleMsgCode.ROLE_NAME_EXIST);
        }
    }


    /**
     *
     * 功能描述: 查询
     *
     * @param:
     * @return:
     */
    public PageInfo<RoleVO> search(RoleCondition roleCondition){
        roleCondition.setId(userService.currentUser().getId());
        List<RoleVO> roleVOS=roleDao.searchList(roleCondition);
        PageInfo<RoleVO> pageInfo=new PageInfo<>(roleVOS);
        return pageInfo;
    }

    /**
     *
     * 功能描述: 根据创建人查找对应角色
     *
     * @param:
     * @return:
     */
    public List<RoleVO> searchByCreateId(){
        Long userId=userService.currentUser().getId();
        Role role=new Role();
        role.setCreateId(userId);
        List<RoleVO> roleVOS= roleDao.searchByRole(role);
        return roleVOS;
    }

    /**
     *
     * 功能描述: 根据角色查找拥有该角色的所有用户
     *
     * @param:
     * @return:
     */
    public PageInfo<UserVO> searchByRole(RoleCondition roleCondition){
        if(Validator.isNull(roleCondition)||Validator.isNull(roleCondition.getId())){
            return null;
        }
        List<UserVO> userVOList=userDao.searchByRole(roleCondition.getId());
        List<UserVO> userVOS=new ArrayList<>();
        PageInfo<UserVO> pageInfo;
        if(Validator.isNotNull(userVOList)){
           userVOList.forEach(userVO -> {
               userVOS.add(userService.deCodeUser(userVO));
           });
            pageInfo = new PageInfo<>(userVOS);
        }else {
            pageInfo = new PageInfo<>(userVOList);
        }
        return pageInfo;

    }

    @ZhhwAnnotation
    public RoleVO modify(RoleVO roleVO){
        if (Validator.isNull(roleVO)){
            return null;
        }
        Role role=roleDao.findById(roleVO.getId());
        if(Validator.isNull(role)){
            throw ServiceException.create(RoleMsgCode.ROLE_NOT_EXIST);
        }
        roleDao.update(role);
        processRolePrivilege(roleVO);
        return roleVO;

    }

    public void delete(RoleVO roleVO){
        if(Validator.isNull(roleVO)){
            return;
        }
        List<UserVO> userVOList=userDao.searchByRole(roleVO.getId());
        if(Validator.isNotNull(userVOList)||userVOList.size()>0){
            throw ServiceException.create(RoleMsgCode.ROLE_EXIST_USER);
        }

        roleDao.deleteById(roleVO.getId());
    }

    List<RoleVO> findByName(String[] roleNmaes){
        List<RoleVO> roleVOS=new ArrayList<>();
        Long userId=userService.currentUser().getId();
        for (int i = 0; i <roleNmaes.length ; i++) {
            RoleVO roleVO;
            roleVO=roleDao.searchByName(roleNmaes[i],userId);
            if(Validator.isNull(roleVO)||Validator.isEmpty(roleVO)){
                roleVO = new RoleVO();
                roleVO.setMsg("角色"+roleNmaes[i]+"不存在或者非当前登录用户创建");
            }
            roleVOS.add(roleVO);
        }
        return roleVOS;

    }
}
